package com.boot.dog.web.security.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.boot.dog.common.auth.DogUser;
import com.boot.dog.common.constant.SecurityConst;
import com.boot.dog.common.enums.UserType;
import com.boot.dog.entities.base.BasePojo;
import com.boot.dog.entities.pojo.Permission;
import com.boot.dog.entities.pojo.Role;
import com.boot.dog.entities.pojo.User;
import com.boot.dog.mapper.PermissionMapper;
import com.boot.dog.mapper.RoleMapper;
import com.boot.dog.mapper.UserMapper;
import com.boot.dog.common.util.SecurityUtil;
import lombok.AllArgsConstructor;

import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: MaxLv
 * @Date: 2019/12/2
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    private final RoleMapper roleMapper;

    private final PermissionMapper permissionMapper;

    @Override
    public DogUser loadUserByUsername(String username){
        DogUser dogUser = SecurityUtil.getUser();
        User user = userMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getUsername, dogUser.getUsername()));
        if (user == null) {
            throw new UsernameNotFoundException("用戶不存在");
        }
        if (user.getDataType() == null) {
            throw new UsernameNotFoundException("用户未分配数据权限");
        }
        List<Role> roles = roleMapper.selectRolesByUserId(user.getId());
        if (CollectionUtil.isEmpty(roles)) {
            throw new UsernameNotFoundException("用戶未分配角色");
        }
        user.setRoles(roles);
        if (StrUtil.equals(UserType.SUPER_ADMIN.code(), user.getUserType())) {
            List<Permission> permissions = permissionMapper.selectList(Wrappers.<Permission>query().lambda().eq(Permission::getStatus, SecurityConst.PERMISSION_STATUS_NORMAL).orderByAsc(Permission::getSortOrder));
            user.setPermissions(permissions);
            return new DogUser(user);
        }
        List<Permission> permissions = permissionMapper.selectByRoleIdsAndDistinct(roles.stream().map(BasePojo::getId).collect(Collectors.toList()), SecurityConst.PERMISSION_STATUS_NORMAL);
        user.setPermissions(permissions);
        return new DogUser(user);
    }

}
